package com.qdlc.p2p.dal.dao.impl;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.dao.AdditionalUserMovieTicketDao;
import com.qdlc.p2p.dal.dto.AdditionalMovieTicketRule;
import com.qdlc.p2p.dal.dto.AdditionalUserMovieTicket;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AdditionalUserMovieTicketModel;

/**
 * Created by liaoxiangkai on 2015/11/24.
 */
@Repository("additionalUserMovieTicketDao")
public class AdditionalUserMovieTicketDaoImpl extends BaseDaoImpl<AdditionalUserMovieTicket> implements AdditionalUserMovieTicketDao {

    /**
     * 查询用户的电影票记录
     *
     * @param user
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageDataList<AdditionalUserMovieTicket> getUserMovieTicketList(User user, int pageNum, int pageSize, int status) {
        QueryParam param = QueryParam.getInstance().addPage(pageNum, pageSize);
        param.addParam("user.userId", user.getUserId());
        if (status != 99) {
            if (status == 2) { //过期的单独拎出来
                param.addParam("expiredTime", SearchFilter.Operators.LTE, DateUtil.getNow());
            } else {
                param.addParam("status", status);
                param.addParam("expiredTime", SearchFilter.Operators.GTE, DateUtil.getNow());
            }
        }
        param.addOrder(OrderFilter.OrderType.ASC, "status");
        param.addOrder(OrderFilter.OrderType.DESC, "addTime");
        return this.findPageList(param);
    }

    /**
     * 后台查询用户电影票列表
     *
     * @param model
     * @return
     */
    @Override
    public PageDataList<AdditionalUserMovieTicketModel> list(AdditionalUserMovieTicketModel model) {
        QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
        param.addOrder(OrderFilter.OrderType.DESC, "addTime");
        if (StringUtil.isNotBlank(model.getSearchName())) {
            SearchFilter orFilter1 = new SearchFilter("user.userName", SearchFilter.Operators.LIKE, model.getSearchName().trim());
            SearchFilter orFilter2 = new SearchFilter("user.realName", SearchFilter.Operators.LIKE, model.getSearchName().trim());
            param.addOrFilter(orFilter1, orFilter2);
        } else {
            //添加用户查询条件
            if (StringUtil.isNotBlank(model.getRealName())) {
                SearchFilter orFilter1 = new SearchFilter("user.userName", SearchFilter.Operators.LIKE, model.getRealName().trim());
                SearchFilter orFilter2 = new SearchFilter("user.realName", SearchFilter.Operators.LIKE, model.getRealName().trim());
                param.addOrFilter(orFilter1, orFilter2);
            }
            //添加规则查询条件
            if (StringUtil.isNotBlank(model.getRuleName())) {
                param.addParam("additionalDrawLotteryRule.name", SearchFilter.Operators.LIKE, model.getRuleName());
            }
            //添加状态查询条件
            if (model.getStatus() != 99) {
                param.addParam("status", model.getStatus());
            }

        }
        param.addPage(model.getPage(), model.getRows());
        PageDataList<AdditionalUserMovieTicket> dataList = this.findPageList(param);
        PageDataList<AdditionalUserMovieTicketModel> modelDataList = new PageDataList<AdditionalUserMovieTicketModel>();
        List<AdditionalUserMovieTicketModel> list = new ArrayList<AdditionalUserMovieTicketModel>();
        if (dataList.getList() != null && dataList.getList().size() > 0) {
            for (AdditionalUserMovieTicket entity : dataList.getList()) {
                AdditionalUserMovieTicketModel additionalUserDrawLotteryModel = AdditionalUserMovieTicketModel.instance(entity);
                //将规则名设置给model
                AdditionalMovieTicketRule movieTicketRule = entity.getAdditionalMovieTicketRule();
                if (null != movieTicketRule && StringUtil.isNotBlank(movieTicketRule.getName()))
                    additionalUserDrawLotteryModel.setRuleName(movieTicketRule.getName());
                //把用户名设置给model
                User user = entity.getUser();
                if (null != user) {
                    additionalUserDrawLotteryModel.setUserName(user.getUserName());
                    if (StringUtil.isNotBlank(user.getRealName())) {
                        additionalUserDrawLotteryModel.setRealName(user.getRealName());
                    }
                }
                list.add(additionalUserDrawLotteryModel);
            }
        }
        modelDataList.setPage(dataList.getPage());
        modelDataList.setList(list);
        return modelDataList;
    }

    /**
     * 更新用户电影票状态
     *
     * @param code   用户兑换码
     * @param status 状态
     * @return
     */
    @Override
    public int updateByExchangeCode(long userId, String code, int status) {
        String sql = "UPDATE AdditionalUserMovieTicket SET status = :status, useTime =:useTime WHERE exchangeCode =:code AND user.userId =:userId";
        Query query = em.createQuery(sql);
        query.setParameter("code", code);
        query.setParameter("useTime", DateUtil.getNow());
        query.setParameter("status", status);
        query.setParameter("userId", userId);
        return query.executeUpdate();
    }

    @Override
    public int updateByOrderNo(String orderNo, String partnerId, String exchangeCode, long userId) {
        String sql = "UPDATE AdditionalUserMovieTicket SET status = :status, partnerId =:partnerId, exchangeCode =:exchangeCode WHERE orderNo =:orderNo AND user.userId =:userId";
        Query query = em.createQuery(sql);
        query.setParameter("orderNo", orderNo);
        query.setParameter("exchangeCode", exchangeCode);
        query.setParameter("partnerId", partnerId);
        query.setParameter("userId", userId);
        query.setParameter("status", AdditionalUserMovieTicketModel.USER_MOVIETICKE_UNUSED);
        return query.executeUpdate();
    }

    @Override
    public int updataById(long id, int status) {
        String sql = "UPDATE AdditionalUserMovieTicket SET status =:status WHERE id =:id";
        Query query = em.createQuery(sql);
        query.setParameter("id", id);
        query.setParameter("status", status);
        return query.executeUpdate();
    }

    @Override
    public int getUserSameMovieCount(long userId, long ruleId) {
        String jpql = "select sum(p.count) from AdditionalUserMovieTicket p where additionalMovieTicketRule.id=:ruleId  and user.userId =:userId";
        Query query = em.createQuery(jpql);
        query.setParameter("ruleId", ruleId);
        query.setParameter("userId", userId);
        Object count = query.getSingleResult();
        if (StringUtil.isBlank(count))
            count = 0;
        return StringUtil.toInt(count.toString());
    }
}
